package se.nestorthon.branding.server.webapp;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import se.nestorthon.branding.entity.Branding;
import se.nestorthon.branding.server.webapp.Initializer.ContextParam;
import se.nestorthon.branding.store.Store;
import se.nestorthon.branding.store.StoreInterface;

public class CreateServlet extends HttpServlet {

	private static class CreateForm
	{
	private static final String NAME = "BrandingName";
	}
	/**
	 * 
	 */
	private static final long serialVersionUID = 3478192440003526575L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.getRequestDispatcher("index.jsp").forward(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		StoreInterface store = Store.getInstance();
		if (ServletFileUpload.isMultipartContent(req)) {
			parseMultiPart(req);
		} else {
			normalPost(req, store);

		}
		req.getRequestDispatcher("createBranding.jsp").forward(req, resp);
	}

	private void normalPost(HttpServletRequest req, StoreInterface store) {
		Branding b = store.createNewBranding(req.getParameter(CreateForm.NAME));
	}

	private void parseMultiPart(HttpServletRequest request) {
		FileItemFactory f = (FileItemFactory) getServletContext().getAttribute(
				ContextParam.FILE_FACTORY.getName());
		ServletFileUpload upload = new ServletFileUpload(f);
		try {
			List<?> files = upload.parseRequest(request);
			for (Object itemO : files) {
				if (itemO != null && itemO instanceof FileItem) {
					FileItem item = (FileItem) itemO;
					if (item.isFormField()) {
						String name = item.getFieldName();
						String value = item.getString();
					} else {
						String fieldName = item.getFieldName();
						String fileName = item.getName();
						String contentType = item.getContentType();
						boolean isInMemory = item.isInMemory();
						long sizeInBytes = item.getSize();
					}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
